<template>
  <div class="order-confirm">
    <div class="container">
      <!-- 进度指示器 -->
      <div class="order-progress">
        <div class="progress-step completed">
          <div class="step-number">✓</div>
          <div class="step-label">选择商品</div>
        </div>
        <div class="progress-line completed"></div>
        <div class="progress-step active">
          <div class="step-number">2</div>
          <div class="step-label">确认订单</div>
        </div>
        <div class="progress-line"></div>
        <div class="progress-step">
          <div class="step-number">3</div>
          <div class="step-label">支付完成</div>
        </div>
      </div>

      <div class="confirm-content">
        <!-- 订单信息 -->
        <div class="order-section">
          <h2>📋 订单信息</h2>
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">订单编号:</span>
              <span class="value">{{ orderInfo.orderNo }}</span>
            </div>
            <div class="summary-item">
              <span class="label">下单时间:</span>
              <span class="value">{{ formatDateTime(orderInfo.createTime) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">订单状态:</span>
              <span class="value status">{{ getStatusText(orderInfo.status) }}</span>
            </div>
          </div>
        </div>

        <!-- 商品清单 -->
        <div class="items-section">
          <h2>🎫 商品清单</h2>
          <div class="items-list">
            <div v-for="item in orderItems" :key="item.id" class="order-item">
              <div class="item-image">
                <img :src="resolveImage(item.posterUrl || item.image)" :alt="item.eventTitle" />
              </div>
              <div class="item-details">
                <h3 class="event-title">{{ item.eventTitle }}</h3>
                <div class="item-info">
                  <div class="info-row">
                    <span class="label">票型:</span>
                    <span class="value">{{ item.ticketType }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">座位:</span>
                    <span class="value">{{ item.seats.join(', ') }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">演出时间:</span>
                    <span class="value">{{ formatDateTime(item.date) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">演出地点:</span>
                    <span class="value">{{ item.venue }}</span>
                  </div>
                </div>
              </div>
              <div class="item-pricing">
                <div class="quantity">数量: {{ item.quantity }}</div>
                <div class="unit-price">单价: ¥{{ item.price }}</div>
                <div class="total-price">小计: ¥{{ item.total }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 价格明细 -->
        <div class="pricing-section">
          <h2>💰 价格明细</h2>
          <div class="pricing-details">
            <div class="price-row">
              <span class="label">商品总额:</span>
              <span class="value">¥{{ orderInfo.subtotal }}</span>
            </div>
            <div class="price-row">
              <span class="label">服务费:</span>
              <span class="value">¥{{ orderInfo.serviceFee }}</span>
            </div>
            <div v-if="orderInfo.couponDiscount > 0" class="price-row discount">
              <span class="label">优惠折扣:</span>
              <span class="value">-¥{{ orderInfo.couponDiscount }}</span>
            </div>
            <div class="price-row total">
              <span class="label">应付总额:</span>
              <span class="value">¥{{ orderInfo.totalAmount }}</span>
            </div>
          </div>
        </div>

        <!-- 联系信息 -->
        <div class="contact-section">
          <h2>📞 联系信息</h2>
          <div class="contact-form">
            <div class="form-group">
              <label for="contactName">联系人姓名 *</label>
              <input 
                type="text" 
                id="contactName" 
                v-model="contactInfo.name"
                placeholder="请输入联系人姓名"
                :class="{ error: errors.name }"
              />
              <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
            </div>
            <div class="form-group">
              <label for="contactPhone">联系电话 *</label>
              <input 
                type="tel" 
                id="contactPhone" 
                v-model="contactInfo.phone"
                placeholder="请输入联系电话"
                :class="{ error: errors.phone }"
              />
              <span v-if="errors.phone" class="error-message">{{ errors.phone }}</span>
            </div>
            <div class="form-group">
              <label for="contactEmail">邮箱地址</label>
              <input 
                type="email" 
                id="contactEmail" 
                v-model="contactInfo.email"
                placeholder="请输入邮箱地址（可选）"
                :class="{ error: errors.email }"
              />
              <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
            </div>
          </div>
        </div>

        <!-- 重要提醒 -->
        <div class="notice-section">
          <h2>⚠️ 重要提醒</h2>
          <div class="notice-content">
            <p>请确认您的联系信息准确无误，我们将通过此信息与您联系。</p>
            <p>演出票一经售出，概不退换，请仔细核对演出信息。</p>
            <p>请在演出开始前30分钟到达现场，凭订单号和身份证件取票。</p>
            <p>如有疑问，请联系客服热线：400-123-4567。</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-section">
          <button @click="goBack" class="btn btn-outline">
            ← 返回购物车
          </button>
          <button 
            @click="confirmOrder" 
            class="btn btn-primary"
            :disabled="isProcessing"
            :class="{ loading: isProcessing }"
          >
            <span v-if="!isProcessing">确认订单并支付</span>
            <span v-else class="loading-content">
              <div class="loading-spinner"></div>
              正在处理...
            </span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { useToastStore } from '@/stores/toast'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()
const toast = useToastStore()
const userStore = useUserStore()

// 状态管理
const isProcessing = ref(false)

// 订单信息
const orderInfo = reactive({
  orderNo: '',
  createTime: new Date(),
  status: 'pending',
  subtotal: 0,
  serviceFee: 0,
  couponDiscount: 0,
  totalAmount: 0
})

// 订单商品
const orderItems = ref([])

// 联系信息
const contactInfo = reactive({
  name: '',
  phone: '',
  email: ''
})

// 表单验证错误
const errors = reactive({
  name: '',
  phone: '',
  email: ''
})

// 计算属性
const isFormValid = computed(() => {
  return contactInfo.name.trim() && 
         contactInfo.phone.trim() && 
         !errors.name && 
         !errors.phone && 
         !errors.email
})

// 生成订单号
const generateOrderNo = () => {
  const timestamp = Date.now()
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `ORD${timestamp}${random}`
}

import { apiClient, BASE_URL } from '@/api/client'
import FallbackPoster from '@/assets/images/phantom-opera.svg'
import { normalizeTicketType } from '@/utils/ticketType'

// 解析商品图片（支持后端上传与本地占位）
const resolveImage = (src) => {
  if (!src) return FallbackPoster
  // 后端上传的相对路径 -> 拼接 BASE_URL
  if (typeof src === 'string' && src.startsWith('/uploads/')) {
    return `${BASE_URL}${src}`
  }
  // 已是完整 URL 或已处理的本地图像
  return src
}

// 格式化日期时间
const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化演出时间
const formatEventDateTime = (date, time) => {
  return `${date} ${time}`
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待支付',
    paid: '已支付',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 表单验证
const validateForm = () => {
  // 清空之前的错误
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })

  let isValid = true

  // 验证姓名
  if (!contactInfo.name.trim()) {
    errors.name = '请输入联系人姓名'
    isValid = false
  } else if (contactInfo.name.trim().length < 2) {
    errors.name = '姓名至少需要2个字符'
    isValid = false
  }

  // 验证电话
  if (!contactInfo.phone.trim()) {
    errors.phone = '请输入联系电话'
    isValid = false
  } else if (!/^1[3-9]\d{9}$/.test(contactInfo.phone.trim())) {
    errors.phone = '请输入正确的手机号码'
    isValid = false
  }

  // 验证邮箱（可选）
  if (contactInfo.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contactInfo.email.trim())) {
    errors.email = '请输入正确的邮箱地址'
    isValid = false
  }

  return isValid
}

// 返回购物车
const goBack = () => {
  router.push('/cart')
}

// 确认订单（调用后端创建订单并持久化）
const confirmOrder = async () => {
  if (!validateForm()) {
    toast.error({ title: '信息填写有误', message: '请检查并完善联系信息' })
    return
  }
  // 检查令牌与登录态
  const hasToken = !!(sessionStorage.getItem('token') || localStorage.getItem('token'))
  if (!userStore.isLoggedIn && !hasToken) {
    toast.error({ title: '请先登录', message: '请登录后再结算' })
    const redirect = router.currentRoute.value.fullPath || '/cart'
    router.push({ path: '/login', query: { redirect } })
    return
  }
  // 若缺少用户ID，尝试拉取个人资料
  if (!userStore?.user?.id) {
    try { await userStore.fetchProfile() } catch (_) {}
  }
  if (!userStore?.user?.id) {
    toast.error({ title: '登录状态异常', message: '请重新登录后再结算' })
    const redirect = router.currentRoute.value.fullPath || '/cart'
    router.push({ path: '/login', query: { redirect } })
    return
  }

  isProcessing.value = true

  try {
    // 按演出分组购物车项目
    const items = [...orderItems.value]
    const eventsMap = new Map()
    for (const it of items) {
      if (!eventsMap.has(it.eventId)) eventsMap.set(it.eventId, [])
      eventsMap.get(it.eventId).push(it)
    }

    // 为每个演出分配唯一票ID并创建订单
    const createdOrders = []
    for (const [eventId, eventItems] of eventsMap.entries()) {
      const ticketsResp = await apiClient.get(`/api/events/${eventId}/tickets?status=1`)
      const available = ticketsResp?.data || []
      const used = new Set()
      const ticketIds = []

      for (const it of eventItems) {
        const typeCode = normalizeTicketType(it.ticketType)
        const candidates = available.filter(t => t.ticketType === typeCode).map(t => t.id)
        let need = it.quantity
        for (const cid of candidates) {
          if (need <= 0) break
          if (used.has(cid)) continue
          used.add(cid)
          ticketIds.push(cid)
          need -= 1
        }
        if (need > 0) {
          throw new Error('部分票型库存不足或票型不匹配，请调整数量或更换票型')
        }
      }

      const body = {
        userId: userStore.user.id,
        eventId,
        ticketIds,
        contactName: contactInfo.name.trim(),
        contactPhone: contactInfo.phone.trim(),
        contactEmail: contactInfo.email.trim(),
        paymentMethod: ''
      }
      const resp = await apiClient.post('/api/orders', body)
      const data = resp?.data ?? resp
      if (!data?.orderNo) throw new Error('创建订单失败')
      createdOrders.push(data)
    }

    cartStore.clearCart()
    toast.success({ title: '订单提交成功', message: '已创建订单，前往订单列表查看' })
    router.push('/orders')
  } catch (error) {
    toast.error({ title: '订单提交失败', message: error?.message || '请稍后重试或联系客服' })
  } finally {
    isProcessing.value = false
  }
}

// 初始化订单数据
const initOrderData = () => {
  // 从购物车获取商品
  orderItems.value = [...cartStore.items]
  
  // 计算价格
  orderInfo.subtotal = cartStore.subtotal
  orderInfo.serviceFee = cartStore.serviceFee
  orderInfo.couponDiscount = cartStore.couponDiscount
  orderInfo.totalAmount = cartStore.finalTotal
  
  // 生成订单号
  orderInfo.orderNo = generateOrderNo()
  
  // 如果购物车为空，返回购物车页面
  if (orderItems.value.length === 0) {
    toast.warning({
      title: '购物车为空',
      message: '请先添加商品到购物车'
    })
    router.push('/cart')
  }
}

// 组件挂载时初始化
onMounted(() => {
  initOrderData()
})
</script>

<style scoped>
.order-confirm {
  min-height: 100vh;
  background: #f8fafc;
  padding: 2rem 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* 进度指示器 */
.order-progress {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  margin-bottom: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  opacity: 0.4;
  transition: all 0.3s ease;
}

.progress-step.active {
  opacity: 1;
  transform: scale(1.1);
}

.progress-step.completed {
  opacity: 1;
  color: #10b981;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
}

.progress-step.active .step-number {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.progress-step.completed .step-number {
  background: #10b981;
  color: white;
}

.step-label {
  font-size: 14px;
  font-weight: 500;
  text-align: center;
}

.progress-line {
  width: 80px;
  height: 2px;
  background: #e5e7eb;
  border-radius: 1px;
}

.progress-line.completed {
  background: #10b981;
}

/* 确认内容 */
.confirm-content {
  display: grid;
  gap: 2rem;
}

/* 通用section样式 */
.order-section,
.items-section,
.pricing-section,
.contact-section,
.notice-section {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-section h2,
.items-section h2,
.pricing-section h2,
.contact-section h2,
.notice-section h2 {
  margin: 0 0 1.5rem 0;
  color: #1e293b;
  font-size: 1.25rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* 订单摘要 */
.order-summary {
  display: grid;
  gap: 1rem;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f1f5f9;
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-item .label {
  color: #64748b;
  font-weight: 500;
}

.summary-item .value {
  color: #1e293b;
  font-weight: 600;
}

.summary-item .value.status {
  color: #f59e0b;
  background: #fef3c7;
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.875rem;
}

/* 商品列表 */
.items-list {
  display: grid;
  gap: 1.5rem;
}

.order-item {
  display: grid;
  grid-template-columns: 120px 1fr auto;
  gap: 1.5rem;
  padding: 1.5rem;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.item-image img {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
}

.item-details {
  flex: 1;
}

.event-title {
  margin: 0 0 1rem 0;
  color: #1e293b;
  font-size: 1.125rem;
  font-weight: 600;
}

.item-info {
  display: grid;
  gap: 0.5rem;
}

.info-row {
  display: flex;
  gap: 0.5rem;
}

.info-row .label {
  color: #64748b;
  font-weight: 500;
  min-width: 80px;
}

.info-row .value {
  color: #1e293b;
}

.item-pricing {
  text-align: right;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  justify-content: center;
}

.quantity,
.unit-price {
  color: #64748b;
  font-size: 0.875rem;
}

.total-price {
  color: #1e293b;
  font-weight: 600;
  font-size: 1.125rem;
}

/* 价格明细 */
.pricing-details {
  display: grid;
  gap: 1rem;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f1f5f9;
}

.price-row:last-child {
  border-bottom: none;
}

.price-row.discount {
  color: #10b981;
}

.price-row.total {
  font-size: 1.25rem;
  font-weight: 700;
  color: #1e293b;
  border-top: 2px solid #e2e8f0;
  margin-top: 0.5rem;
  padding-top: 1rem;
}

/* 联系表单 */
.contact-form {
  display: grid;
  gap: 1.5rem;
}

.form-group {
  display: grid;
  gap: 0.5rem;
}

.form-group label {
  color: #374151;
  font-weight: 500;
  font-size: 0.875rem;
}

.form-group input {
  padding: 0.75rem 1rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 1rem;
  transition: all 0.2s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group input.error {
  border-color: #ef4444;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

.error-message {
  color: #ef4444;
  font-size: 0.875rem;
  margin-top: 0.25rem;
}

/* 重要提醒 */
.notice-content ul {
  margin: 0;
  padding-left: 1.5rem;
  color: #64748b;
  line-height: 1.6;
}

.notice-content li {
  margin-bottom: 0.5rem;
}

/* 操作按钮 */
.action-section {
  display: flex;
  gap: 1rem;
  justify-content: space-between;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.btn {
  padding: 0.875rem 2rem;
  border-radius: 8px;
  font-weight: 600;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-outline {
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-outline:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: 2px solid transparent;
  min-width: 200px;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn.loading {
  cursor: not-allowed;
}

.loading-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-progress {
    flex-direction: column;
    gap: 1rem;
    padding: 1.5rem;
  }
  
  .progress-line {
    width: 2px;
    height: 40px;
  }
  
  .order-item {
    grid-template-columns: 1fr;
    gap: 1rem;
    text-align: center;
  }
  
  .item-pricing {
    text-align: center;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>